<template>
  <div class="chat-page" style="background: linear-gradient(45deg, rgb(253 249 237) 0%, rgb(199 236 253) 100%);">
    <!-- 顶部装饰部分保持不变 -->
    <div style="position: relative; margin: 0px auto; width: 100%; height: 180px; margin-bottom: 30px;">
      <!-- ...原有图片元素... -->
    </div>

    <!-- 消息容器 -->
    <div ref="messageContainer" class="message-container">
      <!-- 快捷问题面板 -->
      <van-cell-group inset style="margin:0">
        <van-tabs v-model:active="active" shrink>
          <!-- ...原有选项卡逻辑... -->
        </van-tabs>
      </van-cell-group>

      <!-- 消息列表 -->
      <div v-for="(msg, index) in messages" :key="index" :class="['message', msg.role, { 'thinking': msg.isThinking }]">
        <div class="bubble">
          <!-- 加载状态 -->
          <template v-if="msg.loading">
            <van-loading size="20" type="spinner">思考中...</van-loading>
          </template>

          <!-- 消息内容 -->
          <template v-else>
            <!-- 思考阶段内容 -->
            <div v-if="msg.thinking" class="thinking-phase">
              <span class="thinking-icon">💡</span>
              {{ msg.thinking }}
            </div>

            <!-- 正式回答内容 -->
            <div v-if="msg.answer" class="answer-phase">
              <div class="answer-header">📖 正式回答</div>
              <div class="answer-content">{{ msg.answer }}</div>
            </div>
          </template>
        </div>
      </div>
    </div>

    <!-- 输入区域 -->
    <div class="input-area">
      <van-field v-model="inputMessage" rows="1" autosize type="textarea" placeholder="请输入问题..."
        @keyup.enter.exact.prevent="sendMessage" />
      <van-button plain type="primary" @click="sendMessage" :loading="isLoading" :icon="svgIconPath" />
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, nextTick, onMounted } from 'vue';
import { questions } from "@/api/chatAI";

// 配置项
const THINKING_MARKER = '</think>';
const AI_RESPONSE_TYPE = {
  THINKING: 'thinking',
  ANSWER: 'answer'
};

// 响应式数据
const messages = reactive([]);
const inputMessage = ref('');
const messageContainer = ref(null);
const isLoading = ref(false);
const active = ref(0);
const questionsList = ref([]);

// 消息处理逻辑
const createMessage = (role, content = '') => ({
  role,
  thinking: '',
  answer: '',
  isThinking: false,
  loading: role === 'assistant',
  responsePhase: AI_RESPONSE_TYPE.THINKING
});

// 流式响应处理
const processContentChunk = (chunk, currentMessage) => {
  let buffer = chunk;

  while (buffer.length > 0) {
    switch (currentMessage.responsePhase) {
      case AI_RESPONSE_TYPE.THINKING:
        const markerIndex = buffer.indexOf(THINKING_MARKER);
        if (markerIndex === -1) {
          currentMessage.thinking += buffer;
          buffer = '';
        } else {
          currentMessage.thinking += buffer.substring(0, markerIndex);
          currentMessage.responsePhase = AI_RESPONSE_TYPE.ANSWER;
          buffer = buffer.substring(markerIndex + THINKING_MARKER.length);
          currentMessage.isThinking = false;
        }
        break;

      case AI_RESPONSE_TYPE.ANSWER:
        currentMessage.answer += buffer;
        buffer = '';
        break;
    }
  }
};

const processStreamResponse = async (response) => {
  const reader = response.body.getReader();
  const decoder = new TextDecoder();
  let buffer = '';

  try {
    while (true) {
      const { done, value } = await reader.read();
      if (done) break;

      buffer += decoder.decode(value, { stream: true });

      // 处理完整行
      let boundary;
      while ((boundary = buffer.indexOf('\n')) >= 0) {
        const line = buffer.slice(0, boundary).trim();
        buffer = buffer.slice(boundary + 1);

        if (!line.startsWith('data: ')) continue;

        const dataContent = line.slice(6);
        if (dataContent === '[DONE]') break;

        try {
          const json = JSON.parse(dataContent);
          const chunk = json.choices?.[0]?.delta?.content || '';
          const currentMessage = messages[messages.length - 1];

          processContentChunk(chunk, currentMessage);
          currentMessage.loading = false;
          currentMessage.isThinking = currentMessage.responsePhase === AI_RESPONSE_TYPE.THINKING;

          requestAnimationFrame(scrollToBottom);
        } catch (e) {
          console.error('解析错误:', e);
        }
      }
    }
  } finally {
    messages[messages.length - 1].loading = false;
    scrollToBottom();
  }
};

// 界面交互
const scrollToBottom = () => {
  nextTick(() => {
    if (messageContainer.value) {
      messageContainer.value.scrollTop = messageContainer.value.scrollHeight;
    }
  });
};

const sendMessage = async () => {
  if (!inputMessage.value.trim()) return;

  try {
    isLoading.value = true;

    // 添加用户消息
    messages.push(createMessage('user', inputMessage.value.trim()));

    // 添加AI消息占位
    messages.push(createMessage('assistant'));

    // 模拟API调用
    const response = await fetch('YOUR_API_ENDPOINT', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ content: inputMessage.value })
    });

    inputMessage.value = '';
    await processStreamResponse(response);
  } catch (error) {
    console.error('请求失败:', error);
  } finally {
    isLoading.value = false;
  }
};

// 初始化
onMounted(() => {
  // questions.value = /* 获取预设问题 */
  scrollToBottom();
});
</script>

<style scoped>
/* 消息气泡样式 */
.message {
  margin: 12px 0;
  transition: all 0.3s ease;

  &.assistant {
    .bubble {
      background: rgba(255, 255, 255, 0.9);
      border-radius: 12px;
      box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);

      .thinking-phase {
        color: #666;
        padding: 12px;
        border-left: 3px solid #4CAF50;
        background: rgba(76, 175, 80, 0.05);
      }

      .answer-phase {
        padding: 12px;

        .answer-header {
          color: #2196F3;
          font-weight: bold;
          margin-bottom: 8px;
        }

        .answer-content {
          line-height: 1.6;
          white-space: pre-wrap;
        }
      }
    }

    &.thinking {
      opacity: 0.8;
      transform: translateY(5px);

      .bubble {
        background: rgba(245, 245, 245, 0.9);
      }
    }
  }
}

/* 输入区域优化 */
.input-area {
  background: rgba(255, 255, 255, 0.95);
  backdrop-filter: blur(5px);
  box-shadow: 0 -4px 12px rgba(0, 0, 0, 0.05);

  :deep(.van-field) {
    background: rgba(245, 245, 245, 0.8);
    border-radius: 20px;
    transition: all 0.3s ease;

    &:focus-within {
      background: white;
      box-shadow: 0 2px 8px rgba(76, 175, 80, 0.15);
    }
  }
}

/* 动画效果 */
@keyframes thinking-pulse {
  0% {
    opacity: 0.8;
  }

  50% {
    opacity: 1;
  }

  100% {
    opacity: 0.8;
  }
}

.thinking-icon {
  animation: thinking-pulse 1.5s infinite;
  margin-right: 8px;
}
</style>